using System.Collections.Generic;
using System.Xml.Linq;
using TDUnit.Common.TestData;

namespace TDUnit.TestDataParsers.XmlParser
{
    public class TableElementParser : ElementParserBase
    {
        private readonly RowElementParser rowParser;

        public TableElementParser(RowElementParser rowParser)
        {
            this.rowParser = rowParser;
        }

        public void Parse(IEnumerable<XElement> tableElements, TestData testData)
        {
            foreach (var tableElement in tableElements)
            {
                var table = ParseTableElement(tableElement, testData);
                rowParser.Parse(tableElement.Elements(tableElement.GetDefaultNamespace() + "Row"), table);
            }
        }

        private static Table ParseTableElement(XElement tableElement, TestData testData)
        {
            var nameAttrib = tableElement.Attribute("Name");
            if (nameAttrib == null)
                throw new XmlTestDataParserException("Table must contain a Name attribute.", tableElement);

            var pkAttrib = tableElement.Attribute("PrimaryKey");
            if (pkAttrib == null)
                throw new XmlTestDataParserException("Table must contain a PrimaryKey attribute.", tableElement);

            var isAutoIdentity = ParseAttributeAsBoolean(tableElement.Attribute("IsAutoIdentity"), "IsAutoIdentity");

            var aliasAttribute = tableElement.Attribute("Alias");
            var aliasString = string.Empty;
            if (aliasAttribute != null)
                aliasString = aliasAttribute.Value;

            return testData.AddTable(nameAttrib.Value, pkAttrib.Value, aliasString).WithAutoIdentity(isAutoIdentity);
        }

    }
}